import React, { useEffect, useState } from 'react'
import { useLocation } from 'react-router-dom'
import { DatePicker, TimePicker, Button } from 'antd'
import 'antd/dist/antd.css'
import moment from 'moment'
import 'moment/locale/zh-cn'
import locale from 'antd/es/date-picker/locale/zh_CN'
import style from './appointment_time.module.css'
import ProjectCard from '../project_reservation/project_card'
import { getProjectList } from '../project_reservation/api'
import { Toast } from 'antd-mobile'
import { setUserProjectList } from './api'
let { con, date_time, more, title } = style

export default function AppointmentTime() {
  const location = useLocation()
  const [project, setProject] = useState([])
  const [date, setDate] = useState('')
  const [time, setTime] = useState('')
  const format = 'HH:mm'
  function onChangeDate(date, dateString) {
    setDate(dateString)
  }

  function onChangeTime(time, timeString) {
    setTime(timeString)
  }

  const getProject = async () => {
    await getProjectList().then(res => {
      setProject(res.data)
    })
  }
  const setUserProject = async obj => {
    await setUserProjectList(obj)
  }
  useEffect(() => {
    getProject()
  }, [])
  return (
    <div className={con}>
      <h1 className={title}>{location.state.props.title}</h1>
      <div className={date_time}>
        <span>请选择预约日期:</span>
        <DatePicker onChange={onChangeDate} locale={locale} />
      </div>
      <div className={date_time}>
        <span>请选择预约时间:</span>
        <TimePicker
          placeholder="请选择时间"
          onChange={onChangeTime}
          defaultValue={moment('00:00', format)}
          format={format}
        />
      </div>
      <Button
        style={{
          marginTop: '12px',
          marginLeft: '50%',
          transform: 'translateX(-50%)',
        }}
        onClick={() => {
          if (date && time) {
            let use = JSON.parse(localStorage.getItem('token'))
            let { title, imgUrl } = location.state.props
            let userId = use.id.toString()
            if (use === null) {
              Toast.show({
                icon: 'fail',
                content: '请先登录',
              })
            } else {
              setUserProject({ userId, time, date, title, imgUrl })
              Toast.show({
                icon: 'success',
                content: '预约成功',
              })
            }
          } else {
            Toast.show({
              icon: 'fail',
              content: '未选择时间',
            })
          }
        }}
        type="primary"
      >
        确认预约
      </Button>
      <h2 className={more}>更多服务内容</h2>
      {project
        .filter(item => item.title !== location.state.props.title)
        .map(item => (
          <ProjectCard
            title={item.title}
            introduce={item.introduce}
            imgUrl={item.imgUrl}
            key={item.id}
          />
        ))}
    </div>
  )
}
